package se.jayway.millionaire.internal.repository;

import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.util.ArrayList;
import java.util.List;
import java.util.Properties;

import se.jayway.millionaire.internal.game.SimpleAnswer;
import se.jayway.millionaire.internal.game.SimpleQuestion;
import se.jayway.millionaire.internal.game.SimpleSolution;
import se.jayway.millionaire.model.game.Answer;
import se.jayway.millionaire.model.repository.Solution;
import se.jayway.millionaire.model.repository.SolutionRepository;


public class FileSolutionRepository implements SolutionRepository {
	
	private final File file;
	private List<SimpleSolution> solutions;
	private int currentSolutionIndex;

	public FileSolutionRepository(File file) {
		this.file = file;
	}
	
	public void populate() {
		InputStream in = null;
		try {
			in = new FileInputStream(file);
			//in = FileSolutionRepository.class.getResourceAsStream("/database.properties");
			if (in == null) {
				throw new IllegalStateException("Missing database.properties file in classpath");
			}
			Properties database = new Properties();
			database.load(in);
			parse(database);
		} catch (IOException e) {
			e.printStackTrace();
		} finally {
			if (in != null) { 
				try {
					in.close();
				} catch (IOException e) {
					e.printStackTrace();
				}
			}
		}
	}
	
	private void parse(Properties database) {
		solutions = new ArrayList<SimpleSolution>();
		int solutionIndex = 1;
		SimpleSolution solution = assembleSolution(database, solutionIndex);
		while (solution != null) {
			solutions.add(solution);
			solutionIndex++;
			solution = assembleSolution(database, solutionIndex);
		}
	}

	private SimpleSolution assembleSolution(Properties database, int solutionIndex) {
		String questionText = database.getProperty(solutionIndex + ".question");
		if (questionText == null) {
			return null;
		}

		List<Answer> answerAlternatives = new ArrayList<Answer>();
		for (int answerIndex = 1; answerIndex < 5; answerIndex++) {
			String answerText = database.getProperty(solutionIndex + ".answer." + answerIndex);
			answerAlternatives.add(new SimpleAnswer(answerIndex, answerText));
		}

		int correctAnswerIndex = Integer.parseInt(database.getProperty(solutionIndex + ".correct")) - 1;

		SimpleQuestion question = new SimpleQuestion(questionText, answerAlternatives, correctAnswerIndex);
		
		return new SimpleSolution(question, answerAlternatives.get(correctAnswerIndex));
	}

	public Solution nextSolution() {
		if (solutions == null) {
			throw new IllegalStateException("SolutionRepository not populated");
		}
		SimpleSolution solution = solutions.get(currentSolutionIndex);
		currentSolutionIndex = (currentSolutionIndex + 1) % solutions.size();
		return solution;
	}
}
